import {ChangeDetectorRef, Component,  ViewEncapsulation} from '@angular/core';

import {MyCrawlerService} from "./crawler.service";
import {MyCrawler} from "./crawler";
import {MyJob} from "./jobs";

@Component({
  selector: 'crawler',
  encapsulation: ViewEncapsulation.None,
  styleUrls:['./crawler.scss'],
  templateUrl: './crawlerTables.html',
})

export class Crawler {


  crawlers:MyCrawler[];
  jobs:MyJob[];
  timer;
  constructor(private cdr: ChangeDetectorRef,private changeDetectorRef:ChangeDetectorRef
              ,protected myCrawlerservice:MyCrawlerService)
  {}

  ngOnInit() : void{

    this.myCrawlerservice.getCrawlers().subscribe((data)=>{
      this.crawlers = data.json();

    });
    this.myCrawlerservice.getJobs().subscribe((data)=>{

      this.jobs=data.json();
      this.SetDisabledButton(this.jobs);
    });

    this.timer = setInterval(()=>{


      for(let i = 0; i< this.jobs.length;i++ ) {

        if (this.jobs[i].status != 'finished') {


          this.myCrawlerservice.getPercent(this.jobs[i].jobId, this.jobs[i].spiderName).subscribe((data) => {

            this.jobs[i].current = data.json();

            this.cdr.detectChanges();

          });

          this.myCrawlerservice.getTotal(this.jobs[i].jobId,this.jobs[i].spiderName).subscribe((data)=>{
            this.jobs[i].total = data.json();

            this.cdr.detectChanges();

          });

        }
      }

    },1000);



  }
  ngOnDestroy(){
    clearInterval(this.timer);
  }

  onStartClick(crawler:MyCrawler){
    this.myCrawlerservice.createCrawlers(crawler.spiderName).subscribe((data1)=>{
      this.myCrawlerservice.getJobs().subscribe((data) => {
        this.jobs=data.json();
        this.SetDisabledButton(this.jobs);
      });
    });

  }

  Cancel(job:MyJob){

    this.myCrawlerservice.cancelCrawlers(job.jobId).subscribe((data1) =>{

      this.myCrawlerservice.getJobs().subscribe((data)=> {
        this.jobs=data.json();
        this.SetDisabledButton(this.jobs);
        console.info(data.json()[0])
      });
    });



  }

  Delete(job:MyJob){
    this.myCrawlerservice.cancelCrawlers(job.jobId).subscribe();
    this.myCrawlerservice.deleteJobByJobId(job.jobId).subscribe((data1)=>{
      this.myCrawlerservice.getJobs().subscribe((data)=> {
        this.jobs=data.json();
        this.SetDisabledButton(this.jobs);
      });
    });
  }

  SetDisabledButton(jobs: MyJob[]){
    for(let i = 0; i< jobs.length;i++ ){
      if (jobs[i].status === 'finished') {
        jobs[i].disabledButton = true;
      }
      else {
        jobs[i].disabledButton = false;
      }

    }
  }
}



